package com.example.filered;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;

public class MainActivity extends AppCompatActivity {


//F"
 /*
    String filePath,fileName;

    TextView textView;
    InputStream inputStreamRawTxt;
    Handler handler=new Handler(){

        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            textView.setText(msg.obj.toString());
        }
    };
*/


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Button bOpen = findViewById(R.id.bOpen);
        TextView tv1 = findViewById(R.id.tv1);
        TextView tv2 = findViewById(R.id.tv2);
        EditText et = (EditText) this.findViewById(R.id.et);


        bOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = loadFromSDFile(et.getText().toString().trim());
                tv2.setText(str);
            }
        });
    }

    private String loadFromSDFile(String fname) {
        fname = "/" + fname;
        String result = null;
        try {
            File f = new File(Environment.getExternalStorageDirectory().getPath() + fname);
            int length = (int) f.length();
            byte[] buff = new byte[length];
            FileInputStream fin = new FileInputStream(f);
            fin.read(buff);
            fin.close();
            result = new String(buff, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(MainActivity.this, "没有找到指定文件", Toast.LENGTH_SHORT).show();
        }
        return result;


        //F''
        /*
          button.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  Log.e("zzz", "onClick:ddasdadadadasda " );
                  initView();
                  Log.e("zzz2", "onClick:ddasdadadadasda " );
                  initData();
                  initEvent();
              }
          });
    }
    private void initView(){

        textView=findViewById(R.id.tv1);

    }

    private void initData(){

        filePath=Environment.getExternalStorageDirectory().getAbsolutePath()
                +"/Download/";
        fileName="printf.txt";
        inputStreamRawTxt =getResources().openRawResource(R.raw.printf);

    }

    private void initEvent(){

        //判断是否有该文件夹，没有则创建一个，生成文件夹之后，再生成文件，不然会出错
        makeDirectory(filePath);
        //在线程中执行耗时操作
        new Thread(new Runnable() {
            @Override
            public void run() {

                //判断是否有该文件，没有则创建一个,并返回true
                if (createNewFile(filePath,fileName)){
                    //返回true说明创建了新的文件，则写入预设内容，
                    //返回false，则说明文件已存在，不需要写入（也不会进入该判断）

                    //将输入流转换成字符串，写入文件
                    String rawTxtString=Stream2String(inputStreamRawTxt);
                    writeTxtToFile(rawTxtString,filePath,fileName);
                }

                //再将文件读取为字符串
                String text=ReadTxtFromSDCard(fileName);
                //显示出来
                Message message=Message.obtain(handler);
                message.obj=text;
                handler.sendMessage(message);

            }
        }).start();
    }

    // 生成文件夹
    public static void makeDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e+"");
        }
    }
    // 生成文件
    public boolean createNewFile(String filePath, String fileName) {
        File file = null;
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
                return true;
            }else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    // 将字符串写入到文本文件中
    public void writeTxtToFile(String stringContent,String filePath, String fileName) {

        String strFilePath = filePath+fileName;
        // 每次写入时，都换行写
        String strContent = stringContent + "\r\n";
        File file = new File(strFilePath);

        try {
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            Log.e("TestFile", "Error on write File:" + e);
        }
    }

    private String Stream2String(InputStream is) {
        //强制缓存大小为16KB，一般Java类默认为8KB
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(is), 16*1024);
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {  //处理换行符
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }


    private String ReadTxtFromSDCard(String filename){

        StringBuilder sb = new StringBuilder("");
        //判断是否有读取权限
        if (!Environment.getExternalStorageState().
                equals(Environment.MEDIA_MOUNTED)) {
            return sb.toString();
        }

        //打开文件输入流
        try {
            FileInputStream input = new FileInputStream(filePath + filename);
            byte[] temp = new byte[1024];

            int len = 0;
            //读取文件内容:
            while ((len = input.read(temp)) > 0) {
                sb.append(new String(temp, 0, len));
            }
            //关闭输入流
            input.close();
        } catch (java.io.IOException e) {
            Log.e("ReadTxtFromSDCard","ReadTxtFromSDCard");
            e.printStackTrace();
        }

        return sb.toString();
    }
     */

////////////
/*
    //读取文本文件中的内容
    public static String ReadTxtFile(String strFilePath)
    {
//        String path = "/raw/text.txt";
        String path = strFilePath;
        String content = ""; //文件内容字符串
        //打开文件
        File file = new File(path);
        //如果path是传递过来的参数，可以做一个非目录的判断
        if (file.isDirectory())
        {
            Log.d("TestFile", "文件不存在.");
        }
        else
        {
            try {
                InputStream instream = new FileInputStream(file);
                if (instream != null)
                {
                    InputStreamReader inputreader = new InputStreamReader(instream);
                    BufferedReader buffreader = new BufferedReader(inputreader);
                    String line;
                    //分行读取
                    while (( line = buffreader.readLine()) != null) {
                        content += line + "\n";
                    }
                    instream.close();
                }
            }
            catch (FileNotFoundException e)
            {
                Log.d("TestFile", "The File doesn't not exist.");
            }
            catch (IOException e)
            {
                Log.d("TestFile", e.getMessage());
            }
        }
        return content;
*/


    }


}